import express from 'express'
import UserService from '../../services/UserService';
import ResponseHelper from '../ResponseHelper';
import { publish } from '../jwt';
import ResultHelper from '../../utils/ResultHelper';

const router = express.Router();

router.post('/login', async function (req, res, next) {
  const body = req.body
  try {
    const result = await UserService.login(body)
    if (result.code === 2000) {
      // 登录成功，颁发 Token 
      publish(res, 3600 * 24 * 7, {
        // @ts-ignore
        c_id: result.data.id,
        // @ts-ignore
        account: result.data.account,
      })
    }

    ResponseHelper.send(result, res)
  } catch (err) {
    next()
  }

})

router.post('/register', async function (req, res, next) {
  const body = req.body
  try {
    const result = await UserService.register(body)

    ResponseHelper.send(result, res)
  } catch (err) {
    // @ts-ignore
    if (err.original.message) {
      // @ts-ignore
      ResponseHelper.send(ResultHelper.error(err.original.message), res)
    } else {
      next()
    }

  }

})


router.get('/count', async function (req, res, next) {
  try {
    const result = await UserService.getUserCount()
    ResponseHelper.send(result, res)
  } catch (err) {
    next()
  }
})

export default router